﻿using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.ApplicationModel.Store;

namespace LicenseHelper
{
    public sealed class LicenseChecker : INotifyPropertyChanged
    {
        static LicenseInformation licenseInformation;
        static bool IsTrialTested = false;


        private bool isTrial = false;
        public bool IsTrial
        {
            get
            {
                if (!IsTrialTested)
                {
                    InitializeLicense();
                }
                return isTrial;
            }
            set
            {
                if (isTrial != value)
                {
                    isTrial = value;
                }
                NotifyPropertyChanged("IsTrial");

            }
        }

        public void InitializeLicense()
        {
            // Initialize the license info for use in the app that is uploaded to the Store.
            // uncomment for release
            //licenseInformation = CurrentApp.LicenseInformation;

            // Initialize the license info for testing.
            // comment the next line for release
            licenseInformation = CurrentAppSimulator.LicenseInformation;
            // Register for the license state change event.
            licenseInformation.LicenseChanged += new LicenseChangedEventHandler(LicenseChangedEventHandler);

            IsTrial = licenseInformation.IsTrial;
        }

        public async static void TestTrialPurchase()
        {
            string x = await CurrentAppSimulator.RequestAppPurchaseAsync(false);
        }


        public void LicenseChangedEventHandler()
        {
            ReloadLicense(); // code is in next steps
        }

        public void ReloadLicense()
        {
            if (licenseInformation.IsActive)
            {
                IsTrial = licenseInformation.IsTrial;
            }
            else
            {
                IsTrial = true;// A license is inactive only when there's an error.
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        // This method is called by the Set accessor of each property. 
        // The CallerMemberName attribute that is applied to the optional propertyName 
        // parameter causes the property name of the caller to be substituted as an argument. 
        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}